package com.juc.juc_project.atomic;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.concurrent.ThreadSafe;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by fangjicai on 2020/3/18.
 */
@Slf4j
@ThreadSafe
public class ConcurrencyTest6 {
    private static AtomicIntegerFieldUpdater<ConcurrencyTest6> updater =
            AtomicIntegerFieldUpdater.newUpdater(ConcurrencyTest6.class, "count");

    //对象属性必须被volatile修饰
    @Getter
    public volatile int count = 100;

    public static void main(String[] args) {

        ConcurrencyTest6 example5 = new ConcurrencyTest6();

        if (updater.compareAndSet(example5, 100, 120)) {
            log.info("update success 1, {}", example5.getCount());
        }

        if (updater.compareAndSet(example5, 100, 120)) {
            log.info("update success 2, {}", example5.getCount());
        } else {
            log.info("update failed, {}", example5.getCount());
        }
    }

}
